﻿using System;
using System.Collections.Generic;
using System.Windows;

using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.Presentation.Events;
using Microsoft.Practices.Composite.Regions;
using Microsoft.Practices.Unity;

using Matchingo.Common.Constants;
using Matchingo.Common.Types.Types;
using Matchingo.Common.Types.Events;
using Matchingo.Common.Types.Interfaces;

namespace Matchingo.Modules.BackgroundModule
{
    public class BackgroundViewModel : DependencyObject, IModule
    {
        #region ========== Private Members ==========

        private static readonly Random RandomGenerator = new Random();

        private readonly IUnityContainer Container;
        private readonly IRegionManager RegionManager;
        private readonly IBackgroundSetProvider BackgroundProvider;
        private readonly IEventAggregator EventAggregator;

        #endregion

        #region ========== Private Properties ==========

        private IBackgroundView View { get; set; }

        #endregion

        #region ========== Constructor ==========

        public BackgroundViewModel(IUnityContainer container, IEventAggregator eventAggregator, 
            IRegionManager regionManager, IBackgroundSetProvider backgroundProvider)
        {
            Container = container;
            RegionManager = regionManager;
            BackgroundProvider = backgroundProvider;
			EventAggregator = eventAggregator;
        }

        #endregion

        #region ========== Public Methods ==========

        public void Initialize()
        {
            View = Container.Resolve<IBackgroundView>();
            View.Initialize(this);

            IRegion region = RegionManager.Regions[CommonConstants.SHELL_REGION_Background];
            region.Add(View);

			SetupBackground(); // setup an initial background

			EventAggregator.GetEvent<GameStartedEvent>().Subscribe(NewGameStarted, ThreadOption.UIThread, true);
        }

        #endregion

        #region ========== Event Handlers ==========

		private void NewGameStarted(Game g)
		{
			SetupBackground();
		}

        #endregion

		#region =========== Private Methods ===========

		private void SetupBackground()
		{
			// get a random background from the current list
			List<Uri> backgroundSet = BackgroundProvider.BackgroundImages;

			if (backgroundSet == null || backgroundSet.Count < 1)
                throw new ArgumentException("BackgroundModule.NewGameStarted() - no backgrounds to choose from");

			int backgroundSeed = RandomGenerator.Next(backgroundSet.Count);

			View.ChangeVisibleImage(backgroundSet[backgroundSeed]);
		}

		#endregion
	}
}
